package 动态规划.经典动态规划题目.编辑距离;

public class 编辑距离_72 {
    public static void main(String[] args) {
        int minDistance = new 编辑距离_72().minDistance("horse", "ros");
        System.out.println(minDistance);
    }

    public int minDistance(String word1, String word2) {
        int m = word1.length();
        int n = word2.length();
        int[][] dp = new int[m + 1][n + 1];

        //base case  没太理解
        for (int i = 1; i <= m; i++) {
            dp[i][0] = i;
        }
        for (int j = 1; j <= n; j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i <= m; i++) {//dp表中下标0是base case，所以这里下标1其实是字符串的第一个字符
            for (int j = 1; j <= n; j++) {

                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    //word1.charAt(i-1)：i=1时，i-1=0；所以是字符串中的第一个字符
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = min(dp[i - 1][j] + 1,
                            dp[i][j - 1] + 1,
                            dp[i - 1][j - 1] + 1
                    );
                }
            }

        }
        return dp[m][n];//存储着整个s1和s2的最小编辑距离
    }

    public int min(int a, int b, int c) {
        return Math.min(a, Math.min(b, c));
    }
}
